package com.vnp.cooking.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;

import com.vnp.cooking.R;
import com.vnp.cooking.utils.Utils;

public class SearchAdapter extends BaseAdapter implements Filterable {

	Context context;
	ArrayList<String> data;
	String filter;

	public SearchAdapter(Context context, ArrayList<String> data) {
		super();
		this.context = context;
		this.data = data;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View v, ViewGroup parent) {
		Holder holder = null;
		if (v == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			v = inflater.inflate(R.layout.item_searchs, parent, false);
			holder = new Holder();

			holder.txtNameCT = (TextView) v.findViewById(R.id.txt_name_ct);

			v.setTag(holder);
		} else {
			holder = (Holder) v.getTag();
		}

		holder.txtNameCT.setText(Utils.toOnlyFirstUpcase(data.get(position)));
		
		holder.txtNameCT.setTypeface(Utils.getTypefaceRegular(context));
		
		return v;
	}

	class Holder {
		TextView txtNameCT;
	}

	@Override
	public Filter getFilter() {
		Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                data = (ArrayList<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < data.size(); i++) {
                    String dataNames = data.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}
